<!-- 学习来源：https://www.bilibili.com/video/BV1Yy4y1K7hy/?spm_id_from=333.337.search-card.all.click&vd_source=7152d744ecc75d82a35a3ceffd3c94ce -->

<template>
  <div ref="eyesContainerRef" class="eyes-follow-container">
    <div ref="eyesBoxRef" class="eyes-box">
      <div class="eyes-row">
        <div class="eye"></div>
      </div>
      <div class="eyes-row">
        <div class="eye"></div>
        <div class="eye"></div>
      </div>
    </div>
  </div>
</template>

<!-- 安装vite-plugin-vue-setup-extend插件让<script setup>标签</script>可以直接自定义组件名 -->
<script setup lang="ts" name="EyesFollow">
const eyesContainerRef = ref()
const eyesBoxRef = ref()
const eyesList: HTMLElement[] = []

// 获取所有眼睛元素
const getEyesElements = () => {
  const eyesRows = []
  eyesRows.push(...eyesBoxRef.value.children)
  eyesRows.forEach((eyesRow) => {
    eyesList.push(...eyesRow.children)
  })
}

const addListeners = () => {
  eyesContainerRef.value.addEventListener("mousemove", eyesFollow)
}
const removeListeners = () => {
  eyesContainerRef.value.removeEventListener("mousemove", eyesFollow)
}

const eyesFollow = (event: MouseEvent) => {
  eyesList.forEach((eye: HTMLElement) => {
    const centerX = eye.getBoundingClientRect().left + eye.clientWidth / 2
    const centerY = eye.getBoundingClientRect().top + eye.clientHeight / 2
    const radian = Math.atan2(event.pageX - centerX, event.pageY - centerY)
    const rotation = radian * ((180 / Math.PI) * -1) + 270
    eye.style.transform = `rotate(${rotation}deg)`
  })
}

onMounted(() => {
  getEyesElements()
  addListeners()
})
onBeforeUnmount(() => {
  removeListeners()
})
</script>

<style lang="scss" scoped>
.eyes-follow-container {
  width: 100%;
  height: 100vh;
  // background: radial-gradient(#f2761e, #ef4921);
  background: radial-gradient(#450101, #000000);
  .eyes-box {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .eyes-row {
      display: flex;
      justify-content: center;
      align-items: center;
      .eye {
        position: relative;
        width: 120px;
        height: 120px;
        display: block;
        background: #ffffff;
        margin: 0 20px;
        border-radius: 50%;
        // box-shadow: 0 5px 45px rgba(0, 0, 0, 0.2), inset 0 0 15px #f2761e, inset 0 0 25px #f2761e;
        box-shadow: 0 5px 45px rgba(0, 0, 0, 0.2), inset 0 0 15px #ff0000, inset 0 0 25px #ff0000;
        &::before {
          content: "";
          width: 45px;
          height: 45px;
          position: absolute;
          top: 50%;
          left: 35px;
          transform: translate(-50%, -50%);
          border-radius: 50%;
          // background: #000000;
          background: #000000;
          // border: 10px solid #683703;
          border: 10px solid #450101;
          box-sizing: border-box;
        }
      }
    }
  }
}
</style>
